package com.wgz.medicalmanagement.service.impl;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.wgz.medicalmanagement.domain.dto.MedicalRecordDTO;
import com.wgz.medicalmanagement.domain.entity.MedicalRecord;
import com.wgz.medicalmanagement.repository.MedicalRecordRepository;
import com.wgz.medicalmanagement.service.MedicalRecordService;

@Service
public class MedicalRecordServiceImpl implements MedicalRecordService {
    
    @Autowired
    private MedicalRecordRepository medicalRecordRepository;

    @Override
    public Page<MedicalRecordDTO> getPatientMedicalRecords(Long patientId, Integer page, Integer size) {
        // 创建分页对象
        Pageable pageable = PageRequest.of(page, size);
        
        // 查询数据
        Page<MedicalRecord> recordPage = medicalRecordRepository.findByPatientIdAndDeletedOrderByVisitDateDesc(patientId, 0, pageable);
        
        // 转换为DTO
        List<MedicalRecordDTO> recordDTOList = recordPage.getContent().stream()
                .map(this::buildMedicalRecordDTO)
                .toList();
        
        return new PageImpl<>(recordDTOList, pageable, recordPage.getTotalElements());
    }
    
    /**
     * 将实体转换为DTO
     * @param record 就诊记录实体
     * @return 就诊记录DTO
     */
    private MedicalRecordDTO buildMedicalRecordDTO(MedicalRecord record) {
        if (record == null) {
            return null;
        }
        
        MedicalRecordDTO dto = new MedicalRecordDTO();
        BeanUtils.copyProperties(record, dto);
        return dto;
    }
} 